﻿

namespace MockingBird.Simulator.Management
{
    using System.Collections.Generic;
    using System.IO;
    using System.Xml;
    using MockingBird.Simulator.Framework.Configuration;

    public class ServiceBuilder : IServiceBuilder
    {
        private IFolderManager folderManager;
        private IHandlerConfigurationManager handlerConfigManager;
        private ServiceConfigurationSettings configSettings;
        private ApplicationConfiguration appConfig;

        public ServiceBuilder(IFolderManager targetFolderManager, IHandlerConfigurationManager targetHandlerConfigManager, ApplicationConfiguration targetAppConfig, ServiceConfigurationSettings targetConfigSettings)
        {
            this.folderManager = targetFolderManager;
            this.handlerConfigManager = targetHandlerConfigManager;
            this.appConfig = targetAppConfig;
            this.configSettings = targetConfigSettings;

        }

        public void UpdateConfigSettings(ServiceConfigurationSettings newConfigSettings)
        {
            this.configSettings = newConfigSettings;

        }

        public void CreateServiceArtifacts()
        {
            // Will be extended in future to download metadata etc
            this.folderManager.CreateServiceFolders(this.configSettings);
        }

        public void CreateEndpointConfiguration(HandlerConfiguration configData)
        {
            string targetFileName = Path.Combine(this.folderManager.GetConfigRoot(), this.configSettings.ConfigFileName);
            this.handlerConfigManager.PersistConfiguration(targetFileName, configData);
        }

        public void CreateHandlerMapping()
        {
            // Initially (v2.1) we create a default mapping. In future versions we can pass the choice of handler etc
            HandlerMapEntry entry = new HandlerMapEntry();
            entry.Endpoint = this.configSettings.EndpointName;
            entry.HandlerName = "BasicSoapMessageHandler";
            this.appConfig.AddHandlerMapEntry(entry);
        }

        #region IServiceBuilder Members


        public void SaveRequestMessages(List<XmlDocument> instances)
        {
            this.folderManager.SaveRequestMessages(instances);
        }

        public void SaveResponseMessages(List<XmlDocument> instances)
        {
            this.folderManager.SaveResponseMessages(instances);
        }

        #endregion
    }
}
